<template>
  <main class="main-content">
    <div class="breadcrumb">
      <span class="breadcrumb-item">设备管理</span>
      <span class="breadcrumb-separator">/</span>
      <span class="breadcrumb-item active">所有设备</span>
    </div>

    <div class="card">
      <!-- 筛选/操作栏 -->
      <div class="table-actions-bar">
        <div class="actions-group">
          <a-button type="primary" @click="openModal('add')">新增设备</a-button>
          <a-button @click="scanModalVisible = true">扫描设备</a-button>
        </div>
        <div class="filter-group">
          <a-tree-select
            v-model:value="filters.locationId"
            style="width: 200px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="locationTree"
            placeholder="请选择安装位置"
            tree-default-expand-all
            allow-clear
            :field-names="{ children: 'children', label: 'name', value: 'id' }"
          />
          <a-select v-model:value="filters.status" style="width: 120px" placeholder="所有状态" allow-clear>
            <a-select-option value="ONLINE">在线</a-select-option>
            <a-select-option value="OFFLINE">离线</a-select-option>
            <a-select-option value="UNINITIALIZED">未初始化</a-select-option>
          </a-select>
          <a-input-search
            v-model:value="filters.keyword"
            placeholder="输入设备名称/编号"
            style="width: 240px"
            @search="handleSearch"
          />
        </div>
      </div>

      <!-- 数据表格 -->
      <a-table
        :columns="columns"
        :data-source="deviceList"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'name'">
            <div>{{ record.name }}</div>
            <div class="sub-text">{{ record.deviceUid }}</div>
          </template>
          <template v-if="column.key === 'ipAddress'">
            {{ record.ipAddress }}:{{ record.port }}
          </template>
          <template v-if="column.key === 'status'">
            <a-badge :status="getStatusType(record.status)" :text="formatStatus(record.status)" />
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <router-link :to="`/devices/detail/${record.id}`">详情</router-link>
               <a @click="handleEdit(record.id)">编辑</a>
              <a-dropdown>
                <a @click.prevent>更多 <DownOutlined /></a>
                <template #overlay>
                  <a-menu>
                    <a-menu-item @click="handleReboot(record)">重启设备</a-menu-item>
                    <a-menu-item @click="handleDelete(record)" danger>删除</a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>
    <!-- 集成扫描弹窗组件 -->
    <DeviceScanModal 
      v-model:visible="scanModalVisible" 
      @scan-completed="handleScanCompleted" 
    />
    <!-- 新增/编辑弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      width="800px"
      @ok="handleOk"
      :confirm-loading="modalLoading"
      destroy-on-close
    >
      <!-- 使用 v-if 确保每次打开时，DeviceForm 都是一个全新的实例 -->
      <DeviceForm v-if="modalVisible" ref="deviceFormRef" :initial-values="editingDevice" />
    </a-modal>
  </main>
</template>

<script setup>
import { ref, reactive, onMounted, computed  } from 'vue';
import { getLocationTree, getDeviceList, createDevice, updateDevice, deleteDevice, rebootDevice, getDeviceDetail} from '../../api/device';
import { DownOutlined } from '@ant-design/icons-vue';
import { Modal, message } from 'ant-design-vue';
import DeviceScanModal from './DeviceScanModal.vue'; // 引入弹窗组件
import DeviceForm from './DeviceForm.vue'; // 引入表单组件 

// --- 弹窗和表单状态 ---
const modalVisible = ref(false);
const modalLoading = ref(false);
const modalMode = ref('add');
const editingDevice = ref(null);
const deviceFormRef = ref();
const modalTitle = computed(() => modalMode.value === 'add' ? '新增设备' : '编辑设备');

// 【核心改造】新的编辑处理逻辑
const handleEdit = async (deviceId) => {
  // 1. 打开弹窗并进入“加载中”状态
  modalMode.value = 'edit';
  editingDevice.value = { id: deviceId }; // 先传入ID，让表单知道是编辑模式
  modalVisible.value = true;
  modalLoading.value = true; // 让弹窗的确定按钮显示加载状态

  try {
    // 2. 异步获取该设备的完整信息
    const response = await getDeviceDetail(deviceId);
    // 3. 将完整的设备信息赋给 editingDevice，触发 DeviceForm 的 watch
    editingDevice.value = response.data;
  } catch (error) {
    message.error('加载设备信息失败，请重试！');
    modalVisible.value = false; // 加载失败则关闭弹窗
  } finally {
    modalLoading.value = false; // 取消加载状态
  }
};

const openModal = (mode) => {
  if (mode === 'add') {
    editingDevice.value = {}; // 清空数据
    modalMode.value = 'add';
    modalVisible.value = true;
  }
  // 编辑逻辑已移至 handleEdit
};

// 点击弹窗“确定”按钮
const handleOk = async () => {
  const formData = await deviceFormRef.value.validate();
  if (!formData) return; // 校验失败

  modalLoading.value = true;
  try {
    if (modalMode.value === 'add') {
      await createDevice(formData);
      message.success('新增成功');
    } else {
      await updateDevice(editingDevice.value.id, formData);
      message.success('更新成功');
    }
    modalVisible.value = false;
    await fetchDevices(); // 刷新列表
  } catch (error) {
    message.error('操作失败');
  } finally {
    modalLoading.value = false;
  }
};

// --- 表格列定义 ---
const columns = [
  { title: '设备名称/编号', key: 'name' },
  { title: '设备型号', dataIndex: 'model', key: 'model' },
  { title: 'IP地址:端口', key: 'ipAddress' },
  { title: '安装位置', dataIndex: 'locationName', key: 'locationName' },
  { title: '状态', key: 'status' },
  { title: '操作', key: 'action' },
];

// --- 响应式状态 ---
const deviceList = ref([]);
const locationTree = ref([]);
const loading = ref(false);
const filters = reactive({
  keyword: '',
  status: undefined, // undefined 在 antd 中代表“请选择”
  locationId: undefined,
});
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total) => `共 ${total} 条`,
});

// --- API 调用 ---
const fetchLocationTree = async () => {
  try {
    const response = await getLocationTree();
    locationTree.value = response.data;
  } catch (error) {
    message.error('获取位置信息失败！');
    console.error(error);
  }
};

const fetchDevices = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.current - 1, // antd 分页从1开始，后端从0开始
      size: pagination.pageSize,
      keyword: filters.keyword || null,
      status: filters.status || null,
      locationId: filters.locationId || null,
    };
    const response = await getDeviceList(params);
    deviceList.value = response.data.content;
    pagination.total = response.data.totalElements;
  } catch (error) {
    message.error('获取设备列表失败！');
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// --- 事件处理 ---
const handleTableChange = (pager) => {
  pagination.current = pager.current;
  pagination.pageSize = pager.pageSize;
  fetchDevices();
};

const handleSearch = () => {
  pagination.current = 1; // 搜索时回到第一页
  fetchDevices();
};

/**
 * 【最终修正版】处理重启设备的逻辑
 */
const handleReboot = (record) => {
  Modal.confirm({
    title: `确认重启设备 “${record.name}” 吗？`,
    content: '此操作将向设备发送重启指令，设备将短暂离线。',
    okText: '确认重启',
    cancelText: '取消',
    onOk: async () => {
      // 1. 创建加载提示，并保存关闭函数
      const hideLoadingMessage = message.loading('正在发送重启指令...', 0);
      try {
        await rebootDevice(record.id);
        message.success(`设备 “${record.name}” 的重启指令已成功发送！`);
      } catch (error) {  
        message.error(`操作失败: ${error.message || '请检查网络或联系管理员。'}`);
        console.error("Reboot failed:", error);
      } finally {
        // 2. 无论成功还是失败，都在 finally 块中关闭加载提示
        hideLoadingMessage();
      }
    },
  });
};


/**
 * 【最终修正版】处理删除设备的逻辑
 */
const handleDelete = (record) => { // 接收整个 record 对象以显示名称
  Modal.confirm({
    title: `确认删除设备 “${record.name}” 吗？`,
    content: '此操作将从设备台账中永久移除该设备，请谨慎操作。',
    okText: '确认删除',
    okType: 'danger', // 将确认按钮变为红色，以示警告
    cancelText: '取消',
    onOk: async () => {
      // 1. 创建加载提示，并保存关闭函数
      const hideLoadingMessage = message.loading('正在删除中...', 0);
      try {
        await deleteDevice(record.id);
        message.success('设备已成功删除！');
        
        // 刷新列表
        if (deviceList.value.length === 1 && pagination.current > 1) {
            pagination.current--;
        }
        // 调用 fetchDevices() 会自动设置表格的 loading 状态，所以我们不需要手动管理
        await fetchDevices(); 
      } catch (error) {
        message.error(error.response?.data?.message || '删除失败，请重试。');
        console.error("Delete failed:", error);
      } finally {
        // 2. 无论成功还是失败，都在 finally 块中关闭加载提示
        hideLoadingMessage();
      }
    },
  });
};

// --- 辅助函数 ---
const formatStatus = (status) => {
  const map = { ONLINE: '在线', OFFLINE: '离线', UNINITIALIZED: '未初始化' };
  return map[status] || '未知';
};
const getStatusType = (status) => {
  const map = { ONLINE: 'success', OFFLINE: 'error', UNINITIALIZED: 'warning' };
  return map[status] || 'default';
};

// --- 生命周期钩子 ---
onMounted(() => {
  fetchLocationTree();
  fetchDevices();
});

const scanModalVisible = ref(false);

// 处理扫描完成事件
const handleScanCompleted = () => {
  // 扫描完成后，可以选择自动关闭弹窗并跳转
  setTimeout(() => {
    scanModalVisible.value = false;
    router.push('/devices/discover');
  }, 1500); // 延迟1.5秒，让用户看到“完成”状态
};

</script>

<style scoped>
/* 保持与 antd 风格一致的间距 */
.table-actions-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}
.filter-group, .actions-group {
  display: flex;
  gap: 8px;
}
.sub-text {
  font-size: 12px;
  color: #8c8c8c;
}
</style>